package base.moduleLoader {
	import flash.display.DisplayObject;
	import flash.events.Event;
	import flash.system.ApplicationDomain;
	
	import mx.core.FlexVersion;
	import mx.core.IVisualElement;
	import mx.events.FlexEvent;
	import mx.events.ModuleEvent;
	import mx.modules.IModuleInfo;
	import mx.modules.ModuleManager;
	
	import spark.components.Group;

	public class BusinessModuleLoader extends Group {
	
		private var _moduleSwf:String;		

		public function get moduleSwf():String
		{
			return _moduleSwf;
		}

		public function set moduleSwf(value:String):void
		{
			_moduleSwf = value;
		}

		private var _businessParams:Object;

		public function get businessParams():Object
		{
			return _businessParams;
		}

		public function set businessParams(value:Object):void
		{
			_businessParams = value;
		}

		protected var module:IModuleInfo; 
		
		public function BusinessModuleLoader(s:String = null, p:Object = null) {
			super();
			_moduleSwf = s;
			_businessParams = p;
			addEventListener(FlexEvent.CREATION_COMPLETE, initModule);
		}
		
		private function initModule(event:FlexEvent):void{
			removeEventListener(FlexEvent.CREATION_COMPLETE, initModule);
			if(_moduleSwf == null || _moduleSwf == ""){
				throw new Error("Please set swf path");
			}
			module = ModuleManager.getModule(_moduleSwf);
			//module.addEventListener(ModuleEvent.PROGRESS, moduleProgressHandler);
			//module.addEventListener(ModuleEvent.SETUP, moduleSetupHandler);
			module.addEventListener(ModuleEvent.READY, moduleReadyHandler);
			module.addEventListener(ModuleEvent.ERROR, moduleErrorHandler);
			//module.addEventListener(ModuleEvent.UNLOAD, moduleUnloadHandler);
			
			var tempApplicationDomain:ApplicationDomain = ApplicationDomain.currentDomain;
			if(tempApplicationDomain == null && moduleFactory && FlexVersion.compatibilityVersion >= FlexVersion.VERSION_4_0){
				var currentDomain:ApplicationDomain = moduleFactory.info()["currentDomain"];
				tempApplicationDomain = new ApplicationDomain(currentDomain);
			}
			
			module.load(tempApplicationDomain, null, null, moduleFactory);
		}
		
		private function moduleReadyHandler(event:ModuleEvent):void{
			var module:IModuleInfo = event.module;
			module.removeEventListener(ModuleEvent.READY, moduleReadyHandler);
			
			var child:IVisualElement = module.factory.create() as IVisualElement;
				
			if(child){
				addElement(child);
			}else{
				var message:String = resourceManager.getString("modules", "couldNotCreateModule", [module.factory.info()["mainClassName"]]);
				var moduleEvent:ModuleEvent = new ModuleEvent( ModuleEvent.ERROR, false, false, event.bytesLoaded, event.bytesTotal, message, event.module);
				dispatchEvent(moduleEvent);
				throw new Error("Could not create module");
			}
			module.unload();
		}
		
		private function moduleErrorHandler(event:ModuleEvent):void{
			throw new Error("Could not create module");
		}
	}
}